package com.example.web_chat.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

//用来管理用户在线情况(userId 和 webSocketSession之间的关系)
@Configuration
public class OnlineUserManage {
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //用户上线，给哈希表中插入元素
    public void  onLine(Integer userId, WebSocketSession session) {
        if(sessions.get(userId) != null) {
            //防止多开现象
            System.out.println("[" + userId + "] 已经被登录");
            return;
        }
        sessions.put(userId, session);
        System.out.println("[" + userId + "] 上线");
        ConcurrentHashMap.KeySetView<Integer, WebSocketSession> integers = sessions.keySet();
        System.out.println("entries:" + integers);

    }

    //用户下线，给哈希表中删除元素
    public void unLine(Integer userId, WebSocketSession session) {
        WebSocketSession webSocketSession = sessions.get(userId);
        if (session == webSocketSession) {
            //对防止多开作一个响应,不是同一个session，不能够被删除
            sessions.remove(userId);
            ConcurrentHashMap.KeySetView<Integer, WebSocketSession> integers = sessions.keySet();
            System.out.println("[" + userId + "] 下线");
            return;
        }
        System.out.println("[" + userId + "] 下线失败");
    }

    //根据 userId 获取 webSocketSession
    public WebSocketSession getWebSocketSession(Integer userId) {
        return sessions.get(userId);
    }

}

